package pkg

import (
	"github.com/golang-jwt/jwt/v4"
	"time"
)

const JwtSecretKey = "2209a"

const JwtExp = 86400

// @secretKey: JWT 加解密密钥
// @iat: 时间戳
// @seconds: 过期时间，单位秒
// @payload: 数据载体

func GetJwtToken(payload int64) (string, error) {
	claims := make(jwt.MapClaims)
	iat := time.Now().Unix()
	claims["exp"] = iat + JwtExp
	claims["iat"] = iat
	claims["payload"] = payload
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims
	return token.SignedString([]byte(JwtSecretKey))
}

func GetToken(tokenString string) (payload int64, err error) {
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { return []byte(JwtSecretKey), nil })
	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		return int64(claims["payload"].(float64)), err
	} else {
		return 0, nil
	}
}
